package com.wendy.admin.controller;

import com.wendy.admin.domain.bo.SysDeptBo;
import com.wendy.admin.domain.bo.SysRoleBo;
import com.wendy.admin.domain.bo.SysUserBo;
import com.wendy.admin.domain.bo.SysUserRoleBo;
import com.wendy.admin.domain.vo.SysRoleExcelVo;
import com.wendy.admin.domain.vo.SysRoleVo;
import com.wendy.admin.domain.vo.SysUserVo;
import com.wendy.admin.entity.SysRole;
import com.wendy.admin.errorcode.SysRoleError;
import com.wendy.admin.service.ISysDeptService;
import com.wendy.admin.service.ISysRoleService;
import com.wendy.admin.service.ISysUserService;
import com.wendy.common.core.domain.TableDataInfo;
import com.wendy.common.log.annotation.Log;
import com.wendy.common.log.enums.BusinessType;
import com.wendy.common.web.controller.BaseController;
import com.wendy.custom.security.annotation.RequiresPermissions;
import com.wendy.custom.security.utils.SecurityUtils;
import com.wendy.excel.ruoyi.utils.ExcelUtil;
import com.wendy.utils.spring.MapstructUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色信息
 *
 * @author wendy
 */
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @RequiresPermissions("system:role:list")
    @GetMapping("/page")
    public TableDataInfo page(SysRoleBo role) {
        TableDataInfo<SysRoleVo> list = roleService.selectRolePage(role);
        return list;
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRoleBo role) {
        List<SysRole> list = roleService.selectRoleList(role);
        List<SysRoleExcelVo> result = MapstructUtils.convert(list, SysRoleExcelVo.class);
        ExcelUtil<SysRoleExcelVo> util = new ExcelUtil<SysRoleExcelVo>(SysRoleExcelVo.class);
        util.exportExcel(response, result, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @RequiresPermissions("system:role:query")
    @GetMapping(value = "/{roleId}")
    public SysRoleVo getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return MapstructUtils.convert(roleService.selectRoleById(roleId), SysRoleVo.class);
    }

    /**
     * 新增角色
     */
    @RequiresPermissions("system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public int add(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            SysRoleError.ADD_ERROR.formatFire(role.getRoleName());
        } else if (!roleService.checkRoleKeyUnique(role)) {
            SysRoleError.ADD_ROLE_ERROR.formatFire(role.getRoleName());
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return roleService.insertRole(role);

    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public int edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role)) {
            SysRoleError.EDIT_ERROR.formatFire(role.getRoleName());
        } else if (!roleService.checkRoleKeyUnique(role)) {
            SysRoleError.EDIT_ROLE_ERROR.formatFire(role.getRoleName());
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return roleService.updateRole(role);
    }

    /**
     * 修改保存数据权限
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public int dataScope(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        return roleService.authDataScope(role);
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public int changeStatus(@RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(SecurityUtils.getUsername());
        return roleService.updateRoleStatus(role);
    }

    /**
     * 删除角色
     */
    @RequiresPermissions("system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public int remove(@PathVariable Long[] roleIds) {
        return roleService.deleteRoleByIds(roleIds);
    }

    /**
     * 获取角色选择框列表
     */
    @RequiresPermissions("system:role:query")
    @GetMapping("/optionselect")
    public List<SysRoleVo> optionselect() {
        List<SysRole> list = roleService.selectRoleAll();
        return MapstructUtils.convert(list, SysRoleVo.class);
    }

    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/authUser/allocated/page")
    public TableDataInfo allocatedPage(SysUserBo user) {
        TableDataInfo<SysUserVo> list = userService.selectAllocatedPage(user);
        return list;
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/authUser/unallocated/page")
    public TableDataInfo unallocatedPage(SysUserBo user) {
        TableDataInfo<SysUserVo> list = userService.selectUnallocatedPage(user);
        return list;
    }

    /**
     * 取消授权用户
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public int cancelAuthUser(@RequestBody SysUserRoleBo userRole) {
        return roleService.deleteAuthUser(userRole);
    }

    /**
     * 批量取消授权用户
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public int cancelAuthUserAll(Long roleId, Long[] userIds) {
        return roleService.deleteAuthUsers(roleId, userIds);
    }

    /**
     * 批量选择用户授权
     */
    @RequiresPermissions("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public int selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        return roleService.insertAuthUsers(roleId, userIds);
    }

    /**
     * 获取对应角色部门树列表
     */
    @RequiresPermissions("system:role:query")
    @GetMapping(value = "/deptTree/{roleId}")
    public Map<String, Object> deptTree(@PathVariable("roleId") Long roleId) {
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysDeptBo()));
        return ajax;
    }
}
